/*!
 @header PersonalInfoViewController.m
 @author 周益
 @version 1.0.0 2013/02/05 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "PersonalViewController.h"
#import "Config.h"
#import "Helper.h"
#import "RTLabel.h"
#import "DynamicDetailViewController.h"
#import "CirclePickerViewController.h"
#import "JMFBase.h"
#import "CellFactory.h"
#import "ASImageView.h"
#import "UIViewController+MJPopupViewController.h"
#import "ReportingViewController.h"
#import "MJRefresh.h"

//  -----------------------类详细介绍-----------------------
//
//  <功能描述>：加载更多
//  	<实现描述>：持有一个BaseRefreshViewController实例替代继承UITableViewController，并且适应BaseRefreshViewControllerDelegate，
//                实现相应的代理方法，通过BaseRefreshViewController的实例变量去控制是否刷新或者是否是下拉刷新或者加载更多。
//  	<注意事项>：PersonalInfoViewController不能以tableview处理，所以就无法继承BaseRefreshViewController。
//                必须适应BaseRefreshViewControllerDelegate,并且持有BaseRefreshViewController一个实例。
//
//  <#更多功能...#>
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述              版本
//
// <#修改人#> <#修改时间#>    <#修改描述#>          <#版本#>

@interface PersonalInfoViewController ()<MJRefreshBaseViewDelegate>

@end

@implementation PersonalInfoViewController
{
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

/*!
 @abstract 指定用户id实例化PersonalInfoViewController
 @discussion 实例化PersonalInfoViewController应该被调用的方法。
 @param personId 用户id
 @result PersonalInfoViewController实例
 */
- (id)initWithPersonId:(NSInteger)personId
{
    self = [super init];
    if (self) {
        _personId = personId;
    }
    return self;
}

- (id)initWithPersonId:(NSInteger)personId and:(NSString *)fromAppKey
{
    self = [super init];
    if (self) {
        _personId = personId;
        
        if ([fromAppKey isEqualToString:_CONFIG_APP_KEY]) {
            
            _fromAppKey = nil;
        }
        else {
            
            _fromAppKey = fromAppKey;
        }
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
    //绘制出个人信息页面
    _personalInfoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 173)];
    _personalInfoView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dynamic_bg_003@2x" ofType:@"png"]]];
    
    
    //头像
    ASImageView *avatarImageView = [[ASImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
    [_personalInfoView addSubview:avatarImageView];
    
    //姓名
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(avatarImageView.frame.origin.x + avatarImageView.frame.size.width + 10, 20, 80, 20)];
    nameLabel.font = _SYS_FONT_004;
    nameLabel.lineBreakMode = UILineBreakModeWordWrap;
    
    [_personalInfoView addSubview:nameLabel];
    
    //性别
    UIImageView *genderImageView = [[UIImageView alloc] initWithFrame:CGRectMake(nameLabel.frame.origin.x + nameLabel.frame.size.width, 23, 13, 13)];
    [_personalInfoView addSubview:genderImageView];
    
    //卖家等级label及其值
    UILabel *sellerLevelLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 20, 55, 12)];
    UILabel *sellerLevelValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(sellerLevelLabel.frame.origin.x + sellerLevelLabel.frame.size.width + 3, 20, 50, 12)];
    
    sellerLevelLabel.font = _SYS_FONT_001;
    sellerLevelValueLabel.font = _SYS_FONT_001;
    
    sellerLevelLabel.textColor = _SYS_COLOR_002;
    sellerLevelValueLabel.textColor = [UIColor colorWithRed:119/255.0 green:156/255.0 blue:1/255.0 alpha:1.0f];
    
    sellerLevelLabel.text = _L(@"title_name_04");   //卖家等级：
    
    [_personalInfoView addSubview:sellerLevelLabel];
    [_personalInfoView addSubview:sellerLevelValueLabel];
    
    
    //认证情况label及其值
    UILabel *authStatusLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 35, 55, 12)];
    UILabel *authStatusValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(authStatusLabel.frame.origin.x + sellerLevelLabel.frame.size.width + 3, 35, 50, 12)];
    
    authStatusLabel.font = _SYS_FONT_001;
    authStatusValueLabel.font = _SYS_FONT_001;
    
    authStatusLabel.textColor = _SYS_COLOR_002;
    authStatusValueLabel.textColor = [UIColor colorWithRed:119/255.0 green:156/255.0 blue:1/255.0 alpha:1.0f];
    
    
    authStatusLabel.text = _L(@"title_name_05");   //认证情况：
    
    [_personalInfoView addSubview:authStatusLabel];
    [_personalInfoView addSubview:authStatusValueLabel];
    
    //个人销售信息
    //售出信息
    RTLabel *goodsBeSoldLabel = [[RTLabel alloc] initWithFrame:CGRectMake(10, 90, 80, 20)];
    goodsBeSoldLabel.font = _SYS_FONT_001;
    
    [_personalInfoView addSubview:goodsBeSoldLabel];
    
    
    //推荐信息
    RTLabel *goodsBeRecommendedLabel = [[RTLabel alloc] initWithFrame:CGRectMake(120, 90, 80, 20)];
    goodsBeRecommendedLabel.font = _SYS_FONT_001;
    
    [_personalInfoView addSubview:goodsBeRecommendedLabel];
    
    
    //达成交易信息
    RTLabel *goodsBeDealtLabel = [[RTLabel alloc] initWithFrame:CGRectMake(230, 90, 80, 20)];
    goodsBeDealtLabel.font = _SYS_FONT_001;
    
    [_personalInfoView addSubview:goodsBeDealtLabel];
    
    //是否在用户圈子内的文字描述以及按钮
    
    UILabel *isInLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 135, 200, 20)];
    isInLabel.textColor = _SYS_COLOR_002;
    isInLabel.backgroundColor = [UIColor clearColor];
    isInLabel.font = _SYS_FONT_004;
    
    [_personalInfoView addSubview:isInLabel];
    
    
    UIButton *circleButton = [[UIButton alloc] initWithFrame:CGRectMake(230, 130, 70, 29)];
    
    [circleButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_btn_002_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [circleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    circleButton.titleLabel.font = _SYS_FONT_004;
    
    [circleButton addTarget:self action:@selector(circleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_personalInfoView addSubview:circleButton];
    
    //绘制出动态tableview

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _personalInfoView.frame.origin.y + _personalInfoView.frame.size.height - 2, _SYS_FRAME_WIDTH, _SYS_SCREEN_HEIGHT - 173 - 60) style:UITableViewStyleGrouped];

    if (iOS7) {
        _tableView.frame = CGRectMake(0, _personalInfoView.frame.origin.y + _personalInfoView.frame.size.height - 2, _SYS_FRAME_WIDTH, _SYS_SCREEN_HEIGHT - 173 - 60 + 44 + 20);
    }
    _tableView.backgroundColor = _SYS_COLOR_BACKGROUND;
    _tableView.backgroundView = nil;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;

    _dynamicDataSource = [NSMutableArray new];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self requestUserAllInfo];
}

#pragma mark - TableView DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return _dynamicDataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //获取一条动态信息
    NSDictionary* dynamic = [_dynamicDataSource objectAtIndex:indexPath.section];
    
    #warning: 这里要优化，使用静态的形式
    NSArray* Cellidentifiers = [NSArray arrayWithObjects:@"Cell_Info", @"Cell_Mood", @"Cell_Goods", @"Cell_Recommend", nil];
    UITableViewCell *cell;

    NSInteger type = [[dynamic objectForKey:@"type"] integerValue];
    NSInteger cellType = type;
    //使用Light类，使界面变得短一些
    if (type == DynamicCategoryProduct) {
        type = 6;
    }
    else if (type == DynamicCategoryRecommend) {
        type = 7;
    }
    else if (type == DynamicCategoryMood) {
        type = 5;
    }
    
    //根据不同的动态类型，获取队列中的不同复用对象
    cell = [tableView dequeueReusableCellWithIdentifier:[Cellidentifiers objectAtIndex:cellType]];
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[Cellidentifiers objectAtIndex:cellType]];
        [CellFactory makeCell:cell forName:type];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    [CellFactory drawCell:cell forName:type withDictionary:dynamic];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 2.5f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 2.5f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = 0.0f;
    
//    if (indexPath.row == 1) {
    
        NSDictionary *dynamic = [_dynamicDataSource objectAtIndex:indexPath.section];
        NSInteger type = [[dynamic objectForKey:@"type"] intValue];
        //如果type是产品/推荐信息就是用Light类，使界面变得短一些
        if (type == DynamicCategoryProduct) {
            type = 6;
        }
        else if (type == DynamicCategoryRecommend) {
            type = 7;
        }
        else if (type == DynamicCategoryMood) {
            type = 5;
        }
        height = [CellFactory heightForName:type withDictionary:dynamic];
//        height = [CellFactory heightForName:[[dynamic objectForKey:@"type"] intValue] withDictionary:dynamic];
//    }
//    else {
//        height = [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
//    }
    
    return height;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dynamicIsSelected = [_dynamicDataSource objectAtIndex:[indexPath section]];
    
    NSInteger dynamicId = [[dynamicIsSelected objectForKey:@"id"] integerValue];
    
    //DynamicCategory枚举从1开始
//    DynamicCategory category = [[dynamicIsSelected objectForKey:@"type"] integerValue];
    
    DynamicDetailViewController *trendDetailVC = [[DynamicDetailViewController alloc] initWithID:dynamicId];
    trendDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:trendDetailVC animated:YES];
    
}

#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

///////////////////////////////////
#pragma mark - 更多按钮点击 和 逻辑处理

- (void)moreButtonEvent:(id)sender
{
    UIActionSheet* actionSheet;
    
    if (_isShield) {
        
        actionSheet = [[UIActionSheet alloc] initWithTitle:Nil delegate:(id)self cancelButtonTitle:_L(@"btn_no_01") destructiveButtonTitle:nil otherButtonTitles:_L(@"btn_yes_41"), _L(@"btn_yes_42"), nil];
    }
    else {

        actionSheet = [[UIActionSheet alloc] initWithTitle:Nil delegate:(id)self cancelButtonTitle:_L(@"btn_no_01") destructiveButtonTitle:nil otherButtonTitles:_L(@"btn_yes_40"), _L(@"btn_yes_42"), nil];
    }
    
    actionSheet.tag = 100;
    [actionSheet showInView:self.view];
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //更多按钮用的
    if (actionSheet.tag == 100) {
        
        //点击的第一个按钮，屏蔽/解除屏蔽
        if (buttonIndex == 0) {
            
            JSONRequest* request = [[JSONRequest alloc] init];
            request.URLString = _isShield ? _JSON_URL_BLACKLIST_RECOVER : _JSON_URL_BLACKLIST_ADD;
            request.delegate = (id)self;
            request.successSelector = @selector(blacklistRequestSuccessSelector:);
            request.hudOn = true;
            request.hudTitle = _L(@"title_loading_01");
            [request setValue:_userInfo[@"id"] forParameter:@"blacklistUserId"];
            [request asynchronous];
        }
        else if (buttonIndex == 1) {
            
            ReportingViewController* reportingViewController = [[ReportingViewController alloc] initWithCategory:ReportingCategoryPeople withID:[_userInfo[@"id"] longValue]];
            reportingViewController.delegate = (id)self;
            [self presentPopupViewController:reportingViewController animationType:MJPopupViewAnimationSlideLeftRight];

        }
    }
}


- (void)blacklistRequestSuccessSelector:(NSDictionary *)dict
{
    //屏蔽成功的话，要改变屏蔽状态_isShield=false
    if ([dict[@"status"] intValue] == 1) {

        _isShield = !_isShield;
        [Helper showAllTextDialog:dict[@"message"] inView:nil];
    }
    else {
        
        [Helper showUTF8String:dict[@"message"]];
    }
}

#pragma mark -


#pragma mark - ReportingViewControllerDelegate

- (void)reportingViewControllerDidFinish
{
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationSlideLeftRight];
}



/*!
 @abstract 圈子相关按钮事件
 */
- (void)circleButtonEvent:(id)sender
{
    if ([_userInfo[@"type"] intValue] != 2) {
        
        [Helper showAlertWithTitle:_L(@"alert_133") andMessage:nil];
        return;
    }
    
    CirclePickerViewController *circlePickerVC = [[CirclePickerViewController alloc] initWithStyle:UITableViewStyleGrouped];
    circlePickerVC.delegate = self;
    
    //将_circleDataSource数组元素转化为Circle对象
    circlePickerVC.pickedCircles = _circleDataSource;
    
    UINavigationController *_circlePickerNC = [[UINavigationController alloc] initWithRootViewController:circlePickerVC];
//    [_circlePickerNC.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg_header"] forBarMetrics:UIBarMetricsDefault];
//    _circlePickerNC.navigationBar.titleTextAttributes = _SYS_NAVIGATIONBAR_TITLETEXTATTRIBUTES;

    [Helper navigationControllerCommonStyle:_circlePickerNC];
    [self.navigationController presentModalViewController:_circlePickerNC animated:YES];
    
}


#pragma mark - CirclePickerViewController Delegate

- (void)circlesPicked:(NSArray *)circles
{
    
    NSString *mobiles = @"";
    if (circles && circles.count != 0) {
        //将多个圈子ID用逗号隔开
        
        for (int i = 0; i < circles.count; i++) {
            
            //如果是最后一个则不添加“，”
            if (i == circles.count - 1) {
                mobiles = [mobiles stringByAppendingFormat:@"%@", [[circles objectAtIndex:i] objectForKey:@"id"]];
            }else{
                mobiles = [mobiles stringByAppendingFormat:@"%@,", [[circles objectAtIndex:i] objectForKey:@"id"]];
            }
        }
    }

    // 接收用户修改后或未修改的圈子
    // 如果最初的圈子数组为空，那么直接请求，如果不为空，那么判断内容是否一样，不一样则删除以前的再请求添加，
    // 一样则不管
    //circles为用户已选择的圈子数组，_cicleDataSource为服务器所返回的圈子数组，用户更新后_cicleDataSource也要跟着更新；
    
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_MEMBER_CHANGE_RELATION];

    [request setValue:mobiles forParameter:@"circleIds"];
    [request setValue:[NSString stringWithFormat:@"%d", _personId] forParameter:@"targetUserId"];
    NSDictionary* responseData = [request synchronous];
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];
    if (jmf.status != JMStatusSucceed) {
        [Helper easyShowJMFStatus:jmf];
    }
    
    
    //修改成功后重设_circleDataSource
    //\\\\\\\\\\\\\\\\\\\\此处remove会异常///////////////////
    //    [_circleDataSource removeAllObjects];
    _circleDataSource = [[NSMutableArray alloc] initWithArray:circles];
    
}

#pragma mark - 私有方法

/*!
 @abstract 向服务器请求用户详细个人信息
 */
- (void)requestUserAllInfo
{
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_GET_DETAILINFO];
    request.delegate = self;
    request.hudOn = YES;
    request.hudTitle = _L(@"title_loading_01");
    
    [request setValue:[NSString stringWithFormat:@"%d", _personId] forParameter:@"peopleId"];
    [request asynchronous];
}

/*!
 @abstract 通过checkid查询向服务器请求更多的动态
 @param checkId 需要分页功能时，传入此id，即数据源中最后一条数据的ID
 */
- (void)dynamicOtherListRequestWithCheckId:(NSString *)checkId
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_DYNAMIC_OTHER_LIST];
    request.delegate = self;
    [request setSuccessSelector:@selector(dynamicOtherListRequestDidSuccess:)];
    
    //id不为空，说明用户在加载更多
    if(checkId != nil){
        
        [request setValue:checkId forParameter:@"checkId"];
        
        [request setSuccessSelector:@selector(moreDynamicsDidReceived:)];
    }
    
    if (_fromAppKey != nil) {

        [request setValue:_fromAppKey forParameter:@"fromAppKey"];
    }
    [request setValue:[_userInfo objectForKey:@"id"] forParameter:@"userId"];
    [request asynchronous];
}

/*!
 @abstract 为个人信息view填充值
 @discussion 此方法应该在请求用户个人信息成功后才被调用
 */
- (void)setUserInfo
{
    
    NSArray *views = [_personalInfoView subviews];
    
    //头像
    UIImageView *avatarImageView = [views objectAtIndex:0];
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[_userInfo objectForKey:@"previewAvatar"]]];
    avatarImageView.image = [UIImage imageWithData:imageData];
    
    //姓名
    UILabel *nameLabel = [views objectAtIndex:1];
    
    nameLabel.text = [_userInfo objectForKey:@"realName"];
    CGSize size = [nameLabel.text sizeWithFont:_SYS_FONT_004 constrainedToSize:nameLabel.frame.size lineBreakMode:UILineBreakModeWordWrap];
    nameLabel.frame = CGRectMake(avatarImageView.frame.origin.x + avatarImageView.frame.size.width + 10, 20, size.width, 20);
    
    //title
    [self.navigationItem setTitle:[_userInfo objectForKey:@"realName"]];
    
    //性别
    UIImageView *genderImageView = [views objectAtIndex:2];
    
    genderImageView.frame = CGRectMake(nameLabel.frame.origin.x + nameLabel.frame.size.width + 10, 23, 13, 13);
    
    if ([[_userInfo objectForKey:@"sex"] integerValue] == 1) {
        genderImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dynamic_icon_001@2x" ofType:@"png"]];
    }else{
        genderImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dynamic_icon_002@2x" ofType:@"png"]];
    }
    
    //卖家认证
    UILabel *sellerLevelValueLabel = [views objectAtIndex:4];
    sellerLevelValueLabel.text = [[_sellerService objectForKey:@"type"] isEqualToString:@""] ? _L(@"title_12") : [_sellerService objectForKey:@"type"];   //未开通
    
    //用户等级
    UILabel *authStatusValueLabel = [views objectAtIndex:6];
    authStatusValueLabel.text = [_userInfo objectForKey:@"certStatus"];
    
    //交易信息栏
    
    RTLabel *goodsBeSoldLabel = [views objectAtIndex:7];
    NSInteger productCount = [[_userStatistics objectForKey:@"productCount"] integerValue];
    
    goodsBeSoldLabel.text = [NSString stringWithFormat:_L(@"tpl_01"), productCount];
    
    RTLabel *goodsBeRecommendedLabel = [views objectAtIndex:8];
    NSInteger recommendCount = [[_userStatistics objectForKey:@"recommendCount"] integerValue];
    goodsBeRecommendedLabel.text = [NSString stringWithFormat:_L(@"tpl_02"), recommendCount];
    
    RTLabel *goodsBeDealtLabel = [views objectAtIndex:9];
    NSInteger transactionCount = [[_userStatistics objectForKey:@"transactionCount"] integerValue];
    goodsBeDealtLabel.text = [NSString stringWithFormat:_L(@"tpl_03"), transactionCount];
    
    UILabel *isInLabel = [views objectAtIndex:10];
    UIButton *circleButton = [views objectAtIndex:11];
    
    if(_personId == [_ACCOUNT_ID integerValue])
    {
        [isInLabel setHidden:YES];
        [circleButton setHidden:YES];
        _personalInfoView.frame = CGRectMake(0, 0, 320, 120);
        _tableView.frame = CGRectMake(0, _personalInfoView.frame.origin.y + _personalInfoView.frame.size.height - 2, 320, _SYS_SCREEN_HEIGHT - 173 - 80 + 44+53);
        
    }
    
    
    //判断是否在圈子
    if (_circleDataSource.count == 0) {
        
        //如果正在邀请
        if (_isInvite) {
            
            circleButton.hidden = true;
            isInLabel.text = _L(@"title_92");
        }
        else {
            isInLabel.text = _L(@"title_circle_04");   //如果你认识他就加入圈子吧
            [circleButton setTitle:_L(@"btn_circle_03") forState:UIControlStateNormal];
        }
        
    }else{
        isInLabel.text = _L(@"title_circle_05");
        [circleButton setTitle:_L(@"btn_circle_04") forState:UIControlStateNormal];
        
    }
    
    [self.view addSubview:_personalInfoView];
    
}

/*!
 @abstract 获取数据源最后一条数据的id
 @discussion 用于分页功能
 @result 数据源最后一条数据的id
 */
- (long)catchTheLastDataSourceId
{
    //是0还是_dataSource.count - 1,服务器端问题
    long lastID = 0;
    if (_dynamicDataSource.count > 0) {
        
        lastID = [[[_dynamicDataSource objectAtIndex:(_dynamicDataSource.count - 1)] objectForKey:@"id"] longValue];
    }
    return lastID;
}

//刷新tableview
- (void)reloadTableView
{
    [_tableView reloadData];
    
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}

#pragma mark - JSONRequest Delegate

- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];

    if (jmf.status == JMStatusSucceed) {
        
        //获得data
        NSDictionary *data = [dict objectForKey:@"data"];

        //屏蔽状态
        _isShield = [data[@"shield"] boolValue];
        
        //邀请状态
        _isInvite = [data[@"invite"] boolValue];
        
        //获得_userInfo
        _userInfo = [data objectForKey:@"peopleUser"];
        
        //如果不是自己，且是普通用户类型，就显示导航栏右边的举报/屏蔽按钮
        if ([_userInfo[@"id"] longValue] != [_ACCOUNT_ID longValue] && [_userInfo[@"type"] intValue] == 2) {
            
            UIButton* moreButton = [Helper buttonWithStyle:ButtonStyleNavigationMore];
            [moreButton addTarget:self action:@selector(moreButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
            UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:moreButton];
            self.navigationItem.rightBarButtonItem = rightBarButtonItem;
        }
        
        //获得卖家服务对象
        _sellerService = [_userInfo objectForKey:@"sellerService"];
        
        //获得用户统计数据
        _userStatistics = [data objectForKey:@"userStatistics"];
        
        //获得个人与我之间的圈友有关系
        if (_circleDataSource == nil) {
            _circleDataSource = [[NSMutableArray alloc] init];
        }
        if (_circleDataSource.count != 0) {
            [_circleDataSource removeAllObjects];
        }
        [_circleDataSource addObjectsFromArray:[data objectForKey:@"circleList"]];
        
        [self setUserInfo];
        //最新20条动态

        [self dynamicOtherListRequestWithCheckId:nil];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

- (void)dynamicOtherListRequestDidSuccess:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        if (_dynamicDataSource.count != 0) {
            [_dynamicDataSource removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            _footer.scrollView = _tableView;
            
            NSMutableArray* filteredUnsaleProducts = [[NSMutableArray alloc] init];
            for (NSDictionary* dynamic in jmf.data) {
                
                //如果产品状态正常，没有停售或下架，就保存
                if (([dynamic[@"product"][@"status"] intValue] == 0)) {
                    
                    [filteredUnsaleProducts addObject:dynamic];
                }
            }
            
            //将保存好的数组载入
            [_dynamicDataSource addObjectsFromArray:filteredUnsaleProducts];
        }
        
        if (_dynamicDataSource.count > 0) {
            _tableView.tableFooterView.hidden = NO;
        }
        else {
            _tableView.tableFooterView.hidden = YES;
        }
        
        [self reloadTableView];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }

}

- (void)moreDynamicsDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            _tableView.tableFooterView.hidden = NO;
            NSMutableArray* filteredUnsaleProducts = [[NSMutableArray alloc] init];
            for (NSDictionary* dynamic in jmf.data) {
                
                //如果产品状态正常，没有停售或下架，就保存
                if (([dynamic[@"product"][@"status"] intValue] == 0)) {
                    
                    [filteredUnsaleProducts addObject:dynamic];
                }
            }
            
            //将保存好的数组载入
            [_dynamicDataSource addObjectsFromArray:filteredUnsaleProducts];
            
        }
        else{
            _tableView.tableFooterView.hidden = YES;
        }
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        //请求初始数据
        //        [self commentsListRequestByCheckId:nil];
    }
    
    //上拉加载更多
    else {
        
        NSString *checkId = [NSString stringWithFormat:@"%ld", [self catchTheLastDataSourceId]];
        
        //发送加载更多的请求,数据接受成功后，设置_reloading
        [self dynamicOtherListRequestWithCheckId:checkId];
    }
}

@end
